// 源插件
import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import { StrToDate, GetDateThreeExcel, GetDateThree } from '@/function';
import { parseExcelDate } from 'read-excel-file-forwps';

// 视图插件
import {
  Checkbox,
  BackTop,
  Empty,
  Spin,
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  InputNumber,
  DatePicker,
  Modal,
  message,
  Badge,
  Divider,
  Steps,
  Radio,
  Upload,
} from 'antd';

// 外部组件
import UploadExcel from '@/components/Upload/UploadExcel';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
// import PositionRuiOptionsTable from "./PositionRuiOptionsTable";

// css OR less预编译器

// 算式
import _pull from 'lodash/pull';
import _indexOf from 'lodash/indexOf';
/**
 *  Describe:数据连接
 *  Created by xjc on 2019/5/15
 */

@connect(({ positionrui, loading }) => ({
  positionrui,
  loading: loading.models.positionruiRule,
}))
@Form.create()
class PositionRui extends PureComponent {
  componentWillMount() {}

  /**
   *  Describe:当前状态
   *  Created by xjc on 2019/5/15
   */

  state = {
    select: ['Data', '期权(DW)'],
    select2: ['郭老师多头股票池', '多头ETF池', '所有持仓股票跑分'],
    select3: ['BOND'],
  };

  uploadData(list, filename) {
    const { dispatch } = this.props;
    const { select } = this.state;
    const fileName = filename.replace('.xls', '');
    const thatDate = GetDateThree(StrToDate(fileName));

    if (select.includes('Data')) {
      const stock = list.Data;
      const uploadListStocks = [];
      let startFlag1 = false;
      let startFlag2 = false;
      for (let i = 0; i < stock.length - 1; i++) {
        if (startFlag2) {
          if (stock[0].length < 24) {
            uploadListStocks.push({
              stock: `${stock[i][0]}`,
              companyname: stock[i][1],
              lastscnum: stock[i][2],
              param1: stock[i][3],
              stockprice: stock[i][4],
              amount: stock[i][5],
              noofshares: stock[i][6],
              sellput: stock[i][7],
              sellputexposure: stock[i][8],
              aq: stock[i][9],
              aqexposure: stock[i][10],
              stocknumber: stock[i][11],
              param2: stock[i][12],
              apa2: stock[i][13],
              dac3: stock[i][14],
              costprice: stock[i][15],
              profit: null,
              profitshares: null,
              stockonhandvalue: stock[i][16],
              sellcall: stock[i][17],
              dq: stock[i][18],
              size: stock[i][21],
            });
          } else {
            uploadListStocks.push({
              stock: `${stock[i][0]}`,
              companyname: stock[i][1],
              lastscnum: stock[i][2],
              param1: stock[i][3],
              stockprice: stock[i][4],
              amount: stock[i][5],
              noofshares: stock[i][6],
              sellput: stock[i][7],
              sellputexposure: stock[i][8],
              aq: stock[i][9],
              aqexposure: stock[i][10],
              stocknumber: stock[i][11],
              param2: stock[i][12],
              apa2: stock[i][13],
              dac3: stock[i][14],
              costprice: stock[i][15],
              profit: stock[i][16] || 0,
              profitshares: stock[i][17] || 0,
              stockonhandvalue: stock[i][18],
              sellcall: stock[i][19],
              dq: stock[i][20],
              size: stock[i][23],
            });
          }
        }
        if (!startFlag1 && stock[i][0] === 'Option') {
          startFlag1 = true;
        }
        if (startFlag1 && stock[i][0] === 'Underlying') {
          startFlag2 = true;
        }
      }
      dispatch({
        type: 'positionrui/UpLoadPositionStocks',
        payload: {
          uploadDate: thatDate,
          uploadList: uploadListStocks,
        },
      });
    }

    if (select.includes('期权(DW)')) {
      const option = list['期权(DW)'];
      const uploadListOptions = [];
      let startFlag3 = false;
      for (let j = 0; j < option.length; j++) {
        if (startFlag3) {
          if (
            option[j][0] === 'Sell Call 卖出股票看涨期权' ||
            option[j][0] === 'Sell Put 卖出股票看跌期权' ||
            option[j][0] === 'Buy Put 買入股票看跌期权' ||
            option[j][0] === 'Buy Call 買入股票看涨期权'
          ) {
            startFlag3 = false;
            continue;
          }

          uploadListOptions.push({
            adddate: thatDate || '空',
            ubsid: option[j][0] || 0,
            unkown1: option[j][1] || '空',
            expiry: parseExcelDate(option[j][2], '-') || '空',
            stock: option[j][3] || '空',
            type: this.SSBB(option[j][4]), // 1sp2sc3bp4bc
            stocknumber: option[j][5] || 0,
            strikeprice: option[j][6] || 0,
            costprice: option[j][8] || 0,
            unkown3: option[j][9] || '空',
            unkown2: option[j][10] || 0,
            tradedate: parseExcelDate(option[j][11], '-') || '空',
            stockprice: option[j][12] || 0,
          });
        }
        if (!startFlag3 && option[j][0] === '#') {
          startFlag3 = true;
        }
      }
      dispatch({
        type: 'positionrui/UpLoadPositionOptions',
        payload: uploadListOptions,
      });
    }
  }

  uploadStock(list) {
    const { dispatch } = this.props;
    const uploadList = [];
    for (let i = 1; i < list['郭老师多头股票池'].length - 1; i++) {
      uploadList.push({ type: 3, stock: list['郭老师多头股票池'][i][0] });
    }
    for (let i = 1; i < list['多头ETF池'].length - 1; i++) {
      uploadList.push({ type: 4, stock: list['多头ETF池'][i][0] });
    }
    for (let i = 1; i < list['所有持仓股票跑分'].length - 1; i++) {
      uploadList.push({ type: 5, stock: list['所有持仓股票跑分'][i][0] });
    }
    dispatch({
      type: 'positionrui/UpLoadStocks',
      payload: { stockList: uploadList },
    });
  }

  uploadData3(list, filename) {
    const { dispatch } = this.props;
    const { select3 } = this.state;

    if (select3.includes('BOND')) {
      const option = list.BOND;
      const uploadListBOND = [];
      const startFlag3 = false;
      const isinId = _indexOf(option[0], 'ISIN');
      const todayPriceId = _indexOf(option[0], '市场价 (参考)');

      for (let j = 1; j < option.length; j++) {
        // uploadListBOND[option[j][6]]=option[j][9]
        uploadListBOND.push({
          isin: option[j][isinId] || null,
          todayPrice: option[j][todayPriceId] || null,
        });
      }
      dispatch({
        type: 'positionrui/UpLoadBOND',
        payload: uploadListBOND,
      });
    }
  }

  /*
    STD(str) {//（日月年）
      const dateStrs = str.split("-");
      const dateMounth = this.ChooseMounth(dateStrs[1]);
      const year = parseInt("20"+dateStrs[2], 10);
      const month = dateMounth?parseInt(dateMounth, 10) - 1:null;
      const day = parseInt(dateStrs[0], 10);
      const date = new Date(year, month, day);
      return date;
    }

    ChooseMounth(str){
      switch (str) {
        case 'Jan':return 1;
        case 'Feb':return 2;
        case 'Mar':return 3;
        case 'Apr':return 4;
        case 'May':return 5;
        case 'Jun':return 6;
        case 'Jul':return 7;
        case 'Aug':return 8;
        case 'Sept':return 9;
        case 'Oct':return 10;
        case 'Nov':return 11;
        case 'Dec':return 12;
        default:return false;
      }
    }
  */

  SSBB(value) {
    // 1234
    if (value === 'Sell Put') {
      return 1;
    }
    if (value === 'Sell Call') {
      return 2;
    }
    if (value === 'Buy Put') {
      return 3;
    }
    if (value === 'Buy Call') {
      return 4;
    }
    return 0;
  }

  onChange(value, e) {
    const { select } = this.state;
    let a;
    if (e.target.checked === true) {
      a = select.push(value);
    } else {
      a = _pull(select, value);
    }
    this.setState({
      select: a,
    });
  }

  runPoints() {
    const { dispatch } = this.props;
    dispatch({
      type: 'positionrui/RunPoints',
    });
  }

  /**
   *  Describe:视图
   *  Created by xjc on 2019/5/15
   */

  render() {
    const {} = this.props;
    const { select, select2, select3 } = this.state;

    return (
      <PageHeaderWrapper title="瑞银上传">
        <Card>
          <Row>
            <UploadExcel upload={this.uploadData.bind(this)} sheets={select} name="数据上传" />
            <Checkbox onChange={this.onChange.bind(this, 'Data')} defaultChecked>
              股票
            </Checkbox>
            <Checkbox onChange={this.onChange.bind(this, '期权(DW)')} defaultChecked>
              期权(DW)
            </Checkbox>
          </Row>
          <br />
          <Row>
            <UploadExcel
              upload={this.uploadStock.bind(this)}
              sheets={select2}
              name="股票代码上传"
            />

            <Button type="primary" onClick={this.runPoints.bind(this)}>
              开始跑分
            </Button>
          </Row>
          <br />
          <Row>
            <UploadExcel upload={this.uploadData3.bind(this)} sheets={select3} name="债券上传" />
          </Row>
        </Card>
      </PageHeaderWrapper>
    );
  }

  componentDidMount() {
    const { dispatch } = this.props;
  }

  componentWillUnmount() {}
}

export default PositionRui;
